<template>
  <div class="system">
    <div class="table">
      <div class="header">
        <Button
          type="primary"
          @click="onExportMembers"
          >导出所有中奖信息</Button
        >
        <Button
          danger
          @click="onDeleteRound(undefined)"
          >删除所有轮次</Button
        >
      </div>
      <div
        v-for="item in rounds"
        :key="item.id">
        <PageHeader :title="` ${displayPrize(item.prize)}(${item.count}个)`">
          <template v-for="(sponsor, index) in item?.zxs" :key="index">
            <img :src="sponsor.icon" alt="企业图标" class="option-icon" />
            <span>{{ sponsor.value }}</span>
            <span v-if="index < (currentRound?.zxs.length || 0) - 1">、</span>
          </template>
           <template #tags>
            <Tag :color="item.state ? 'gray' : 'blue'">{{
              item.state
                ? "抽奖结束"
                : currentRoundID === item.id
                ? "准备已就绪"
                : "未激活"
            }}</Tag>
          </template>
          <template #extra>
            <Tooltip
              :title="
                item.state
                  ? '已抽取完毕'
                  : currentRoundID === item.id
                  ? '已设置为当前抽奖轮次'
                  : '设置为当前抽奖轮次'
              ">
              <Button
                type="primary"
                :disabled="currentRoundID === item.id || item.state"
                @click="onSetCurrentRound(item.id)"
                >设置为当前轮次</Button
              >
            </Tooltip>
            <Tooltip
              title="重置后可重新抽奖"
              v-if="item.state">
              <Button
                danger
                @click="onResetRound(item.id)"
                >重置当前轮次</Button
              >
            </Tooltip>
            <Tooltip title="删除当前配置">
              <Button
                danger
                @click="onDeleteRound(item.id)"
                >删除当前轮次</Button
              >
            </Tooltip>
          </template>
          <div>
            中奖人员：{{ item.winners.name?.join("、") }}
            <span v-if="item.winners.length"
              >共{{ item.winners.length }}个</span
            >
          </div>
        </PageHeader>
      </div>
    </div>
    <div class="action">
      <Form layout="vertical">
        <FormItem label="奖项类型">
          <Select
            v-model:value="currentPrizeClass"
            placeholder="请选择奖项"
            :options="prizeClassOptions" />
        </FormItem>
        <FormItem label="数量">
            <Input
            v-model:value="currentPrizeCount"
            placeholder="请选择抽取个数"
            type="number"
          />
       
        </FormItem>

       <FormItem label="赞助商">
         <Select
            mode="multiple"
            show-search
            v-model:value="zxs"
            placeholder="请选择赞助商"
            @search="handleSearch"
             @change="handleSelectChange"
            :options="zxsName" >
              <!-- 自定义选项渲染 -->
            <template #option="{ value, label, icon }">
              <div class="custom-option">
                <img :src="icon" alt="企业图标" class="option-icon" />
                <span>{{ label }}</span>
              </div>
            </template>
            
            </Select>       
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            @click="onSubmit"
            >下发</Button
          >
        </FormItem>
      </Form>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  PageHeader,
  Select,
  Form,
  FormItem,
  Button,
  message,
  Tag,
  Tooltip,
  Modal,
  Input
} from "ant-design-vue";
import { flatten } from "lodash-es";
import { onMounted, ref ,reactive} from "vue";
import axios from "axios";
import { IRound, displayPrize } from "./interface";
const currentPrizeClass = ref("LUCKY_A");
const currentPrizeCount = ref();

const zxs = ref([]);
const selectedValues = ref([]); // 存储选中的值
const rounds = ref<IRound[]>([]);
const currentRoundID = ref<string | undefined>();

// 新增选项逻辑
const handleSearch = (value: string) => {
  if (!zxsName.some((option) => option.value === value)) {
    const newOption = { value, label: value, icon: "/t1.webp" }; // 默认图标路径
    zxsName.push(newOption);
  }
};

// 选项选中时更新 zxs
const handleSelectChange = (selectedValues: string[]) => {
  zxs.value = selectedValues.map((value) => {
    const option = zxsName.find((item) => item.value === value);
    return option ? { value: option.value, icon: option.icon } : null;
  }).filter(Boolean); // 过滤掉无效的选项
};
const zxsName = reactive([
  { value: "腾讯", label: "腾讯", icon: "/t1.webp" },
  { value: "阿里巴巴", label: "阿里巴巴", icon: "t1.webp" },
  { value: "百度", label: "百度", icon: "t1.webp" },
  { value: "字节跳动", label: "字节跳动", icon: "t1.webp" },
]);
const prizeClassOptions = [
  {
    label: "一等奖 大疆 DJI Osmo Action 4 运动相机",
    value: "FIRST_A",
  },
  {
    label: "一等奖 大疆DJI Mini 4K 超高清迷你航拍无人机",
    value: "FIRST_B",
  },
  {
    label: "一等奖 九号电动滑板车F25升级款",
    value: "FIRST_C",
  },
  {
    label: "二等奖 MARSHALL （马歇尔） WILLEN I1 蓝牙音响",
    value: "SECOND_A",
  },
  {
    label: "二等奖 大疆 DJI Neo 掌上 Vlog 跟拍无人机",
    value: "SECOND_B",
  },
  {
    label: "二等奖 华为FreeClip 耳夹耳机",
    value: "SECOND_C",
  },
  {
    label: "三等奖 京东购物卡",
    value: "THIRD_A",
  },
  {
    label: "三等奖 徕芬Laifen高速吹风机",
    value: "THIRD_B",
  },
  {
    label: "三等奖 小米（MI） 米家喷墨打印一体机",
    value: "THIRD_C",
  },
  {
    label: "三等奖 倍轻松 (breo） seex2pro 曜石黑-眼睛按摩仪",
    value: "THIRD_D",
  },
  {
    label: "幸运奖A",
    value: "LUCKY_A",
  },
  {
    label: "幸运奖B",
    value: "LUCKY_B",
  },
  {
    label: "幸运奖C",
    value: "LUCKY_C",
  },
  {
    label: "幸运奖D",
    value: "LUCKY_D",
  },
  {
    label: "幸运奖E",
    value: "LUCKY_E",
  },
];

const refreshPrize = () => {
  return axios.get("/prize").then((res: any) => {
    rounds.value = res.data?.rounds || [];
    currentRoundID.value = res.data?.currentRoundID;
  });
};
// const handleSelectChange = (selectedValue: string) => {
//   const selectedOption = zxsName.find((option) => option.value === selectedValue);
//   if (selectedOption) {
//     zxs.value = { value: selectedOption.value, icon: selectedOption.icon };
//   }
// };
const getPrize = () => {
  refreshPrize().finally(() => {
    setTimeout(() => {
      getPrize();
    }, 1000);
  });
};

const onSubmit = () => {
  axios.post("/prize", {
      prize: currentPrizeClass.value,
      count: currentPrizeCount.value,
      zxs: zxs.value,
    })
    .then(() => {
      message.success("下发成功");
      refreshPrize();
    });
};

onMounted(() => {
  getPrize();
});

const onDeleteRound = (roundID: string) => {
  Modal.confirm({
    title: () => "确定删除这轮抽奖码？删除后无法恢复",
    onOk() {
      axios
        .post("/prize/reset", {
          roundID: roundID,
        })
        .then(() => {
          message.success("重置成功");
          refreshPrize();
        });
    },
  });
};
const onSetCurrentRound = (roundID: string) => {
  Modal.confirm({
    title: () => "确定设置为当前抽奖轮次吗？",
    onOk() {
      axios
        .post("/prize/setCurrentRound", {
          roundID: roundID,
        })
        .then(() => {
          message.success("设置成功");
          refreshPrize();
        });
    },
  });
};
const onResetRound = (roundID: string) => {
  Modal.confirm({
    title: () => "确定重置这轮抽奖码？删除后无法恢复",
    onOk() {
      axios
        .post("/prize/resetRoundWinners", {
          roundID: roundID,
        })
        .then(() => {
          message.success("重置成功");
          refreshPrize();
        });
    },
  });
};
const onExportMembers = () => {
  const element = document.createElement("a");
  console.log(rounds.value);
  element.setAttribute(
    "href",
    "data:text/plain;charset=utf-8," +
      encodeURIComponent(`
       一等奖成员 大疆 DJI Osmo Action 4 运动相机: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "FIRST_A")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}
       一等奖成员 大疆DJI Mini 4K 超高清迷你航拍无人机: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "FIRST_B")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}
       一等奖成员 九号电动滑板车F25升级款: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "FIRST_C")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}

       二等奖成员 MARSHALL （马歇尔） WILLEN I1 蓝牙音响: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "SECOND_A")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}
       二等奖成员 大疆 DJI Neo 掌上 Vlog 跟拍无人机: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "SECOND_B")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}
       二等奖成员 华为FreeClip 耳夹耳机: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "SECOND_C")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}

       三等奖成员 京东购物卡: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "THIRD_A")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}
       三等奖成员 徕芬Laifen高速吹风机: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "THIRD_B")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}
       三等奖成员 小米（MI） 米家喷墨打印一体机: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "THIRD_C")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}
       三等奖成员 倍轻松 (breo） seex2pro 曜石黑-眼睛按摩仪: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "THIRD_D")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}
       幸运奖A: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "LUCKY_A")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}
       幸运奖B: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "LUCKY_B")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}
       幸运奖C: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "LUCKY_C")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}
       幸运奖D: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "LUCKY_D")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}
       幸运奖E: ${flatten(
         rounds.value
           ?.filter((item) => item.prize === "LUCKY_E")
           .map((item) => item.winners.join("、")) || []
       ).join("、")}
      `)
  );
  element.setAttribute("download", "中奖人员名单");
  element.style.display = "none";
  element.click();
};
</script>

<style lang="less" scoped>
.system {
  width: 100vw;
  height: 100vh;
  display: flex;
}
.table {
  flex: 1;
  border-right: 2px solid #d9d9d9;
}
.ant-page-header {
  border: 1px solid rgb(235, 237, 240);
}
.header {
  display: flex;
  justify-content: space-between;
  padding: 20px;
}
.action {
  padding: 20px;
  width: 400px;
}

:deep(.ant-btn),
:deep(.ant-select) {
  margin-right: 10px;
}
:deep(.ant-select) {
  width: 140px;
  margin-right: 10px;
}
.custom-option {
  display: flex;
  align-items: center;
}

.option-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}
</style>
